package com.sunmnet.j2ee.service.powerdb.designer.impl;

import com.sunmnet.j2ee.core.pub.sqlloader.SqlLoader;
import com.sunmnet.j2ee.dao.BaseDao;
import com.sunmnet.j2ee.entity.powerdb.designer.Version;
import com.sunmnet.j2ee.service.impl.BaseServiceImpl;
import com.sunmnet.j2ee.service.powerdb.designer.PDMService;
import com.sunmnet.j2ee.service.powerdb.designer.VersionService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("/powerdb/designer/versionService")
public class VersionServiceImpl extends BaseServiceImpl<Version, Long> implements VersionService {

	private static final Logger LOG = LogManager.getLogger(VersionServiceImpl.class.getName());

	private static final String CLASS_NAME = VersionServiceImpl.class.getName();


	private static final String SQL_SELECT_PROJECT_REL_VERSION =
			SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_SELECT_PROJECT_REL_VERSION");

	private static final String SQL_SELECT_PROJECT_REL_MODULE =
			SqlLoader.getInstance().getSql(CLASS_NAME, "SQL_SELECT_PROJECT_REL_MODULE");

	@Override
	@Resource(name = "/powerdb/designer/versionDao")
	public void setDao(BaseDao<Version, Long> dao) {
		super.dao = dao;
	}

	@Resource(name = "/powerdb/designer/pdmService")
	private PDMService pdmService;

	/**
	 * 根据工程id获取相关版本
	 *
	 * @param projectId 工程id
	 * @return
	 * @throws Exception
	 */
	@Override
	public List getProjectRelVersion(long projectId) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("projectId", projectId);
		List result = dao.findBySql(SQL_SELECT_PROJECT_REL_VERSION, params);
		LOG.debug("getProjectRelVersion: {} , result: {}", projectId, result);
		return result;
	}

	/**
	 * 将指定工程打包成新版本
	 *
	 * @param obj 新版本对象
	 * @throws Exception
	 */
	@Override
	public void saveVersionOfProject(Version obj) throws Exception {
		LOG.debug("saveVersionOfProject: {}", obj);

		List<Map<String, Object>> result;
		long moduleId;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("projectId", obj.getProjectId());

		try {
			result = dao.findBySql(SQL_SELECT_PROJECT_REL_MODULE, params);
			for (Map module : result) {
				moduleId = Long.parseLong(module.get("id").toString());
				pdmService.copyDatas(moduleId, obj.getId());
			}
		} catch (Exception e) {
			//TODO:删除已保存的版本

			throw e;
		}
	}
}
